package com.ruiyangwang.ListenBook.servlet.album;

import com.ruiyangwang.ListenBook.dataObject.AlbumDO;
import com.ruiyangwang.ListenBook.repository.AlbumRepo;
import com.ruiyangwang.ListenBook.repository.RelationRepo;
import com.ruiyangwang.ListenBook.util.Log;
import com.ruiyangwang.ListenBook.viewObject.UserV0;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syzygy
 * @date 2022/09/20 10:06
 **/
@WebServlet("/studio/album/bind.do")
public class BindDoServlet extends HttpServlet {
    AlbumRepo albumRepo = new AlbumRepo();
    RelationRepo relationRepo = new RelationRepo();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String aid = req.getParameter("aid");
        String[] tid = req.getParameterValues("add-tid");
        Log.println("aid = " + aid);
        for(String temp : tid){
            Log.println(temp);
        }
        HttpSession session = req.getSession(false);
        if (session != null) {
            UserV0 user = (UserV0) session.getAttribute("currentUser");
            if (user != null) {
                AlbumDO albumDo = albumRepo.selectOneByAid(Integer.parseInt(aid));
                if (albumDo == null) {
                    Log.println("要下线的专辑不存在: aid ="+ aid);
                    resp.sendRedirect( "/studio/album/list.html");
                    return;
                }

                if (!albumDo.uid.equals(user.uid)) {
                   Log.println("要下线的专辑不属于这个用户: aid = {}" + aid +"album.uid = {}" +albumDo.uid + " currentUser.uid = {}" + user.uid);
                    resp.sendRedirect("/studio/album/list.html");
                }

               List<Integer> tidList= new ArrayList<>();
                for (String temp:tid) {
                    tidList.add(Integer.parseInt(temp));
                }
                if (!tidList.isEmpty()) {
                    relationRepo.insertBatch(aid, tidList);
                }

                resp.sendRedirect("/studio/album/relate.html?aid=" + aid);
                return;
            }
        }
       Log.println("用户未登录，无法操作");
        resp.sendRedirect("/studio/user/login.html");
    }
}